/*
 * @lc app=leetcode.cn id=992 lang=javascript
 *
 * [992] K 个不同整数的子数组
 */

// @lc code=start
/**
 * @param {number[]} A
 * @param {number} K
 * @return {number}
 */
var subarraysWithKDistinct = function (A, K) {
  return atMostKDistinct(A, K) - atMostKDistinct(A, K - 1);

  // 最多K个字符的子数组数量
  function atMostKDistinct(A, K) {
    const size = A.length;
    const freq = new Array(size + 1).fill(0);
    let res = 0;
    let count = 0;
    let i = 0;
    let j = 0;

    while (j < size) {
      if (freq[A[j]] === 0) {
        count++;
      }
      freq[A[j]]++;
      while (count > K) {
        freq[A[i]]--;
        if (freq[A[i]] === 0) {
          count--;
        }
        i++;
      }
      res += j - i + 1;
      j++;
    }

    return res;
  }
};
// @lc code=end
